package com.example.hotHub.service.impl;

import com.example.hotHub.model.Almanac;
import com.example.hotHub.service.DateWrapperService;
import com.example.hotHub.utils.RestTemplateUtil;
import com.example.hotHub.utils.SimpleMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DateWrapperServiceImpl implements DateWrapperService {

    @Override
    public Almanac getAlmanac(Integer year, Integer month, Integer day) {
        String query = year + "年" + month + "月";
        RestTemplateUtil restTemplateUtil = new RestTemplateUtil();
        String url = "http://opendata.baidu.com/api.php";
        Map<String, Object> params = new HashMap<>();
        params.put("query", query);
        params.put("resource_id", "39043");
        params.put("format", "json");
        params.put("tn", "wisetpl");
        SimpleMap response = restTemplateUtil.doGet(url, params, null, SimpleMap.class);
        List<Almanac> almanacList = response.getList("data", SimpleMap.class).get(0).getList("almanac", Almanac.class);
        for (Almanac almanac : almanacList) {
            if (almanac.getYear().equals(year.toString()) && almanac.getMonth().equals(month.toString()) && almanac.getDay().equals(day.toString())) {
                log.info("成功爬取万年历({}-{}-{}): {}", year, month, day, almanac);
                return almanac;
            }
        }
        log.info("爬取万年历失败");
        return null;
    }
}
